import sys
import os
from tkinter import messagebox
import tkinter as tk
from tkinter import filedialog
import random
import requests
from asteval import Interpreter

aeval = Interpreter()
addonf = []
try:
    with open('GSAddon.ini', 'r', encoding='utf-8') as file:
        addon = file.readlines()
        for q in addon:
            if q.split(" ")[0] != "all":
                addonf.append(q.split(" ")[0])
        #print("已添加插件:"+str(addonf))
except FileNotFoundError:
    print('无法读取GSAddon.ini，因此将不加载GSAddon插件\n注意:这可能会导致兼容性问题')

moshi = 0
nr = sys.argv
nr.pop(0)
add = []
bl = {}
line = 0
def math( ss2 ):
    #print(ss2)
    try:
        # 使用 asteval 计算算式
        result = aeval(ss2)
        return result
    except Exception as e:
        return -1
    """
    else:
    if ss.count("+") == 1 or ss.count("-") == 1 or ss.count("*") == 1 or ss.count("/") == 1:
        if ss.count("+") == 1:
            ss = ss2.split("+")
            a = float(ss[0])
            b = float(ss[1])
            return a + b
        elif ss.count("-") == 1:
            ss = ss2.split("-")
            a = float(ss[0])
            b = float(ss[1])
            return a - b
        elif ss.count("*") == 1:
            ss = ss2.split("*")
            a = float(ss[0])
            b = float(ss[1])
            return a * b
        elif ss.count("/") == 1:
            ss = ss2.split("/")
            a = float(ss[0])
            b = float(ss[1])
            return a / b
    elif ss2.count("**") == 1:
        ss = ss2.split("**")
        a = float(ss[0])
        b = float(ss[1])
        return a ** int(b)
    else:
        print("Err:目前还不支持综合算式哦~")
        s = "".join(ss)
        if ss.count("*") >= 1 or ss.count("/") >= 1:
            if ss.find("*") == -1:
                math(ss[0:ss.find("/") - 2]+str(int(ss[ss.find("/")+1]) / int(ss[ss.find("/")-1])+ss[0:ss.find("/") + 2]))
            elif ss.find("/") == -1:
                math(ss[0:ss.find("*") - 2]+str(int(ss[ss.find("*") + 1]) / int(ss[ss.find("*")-1])+ss[0:ss.find("*") + 2]))
            elif ss.find("*") < ss.find("/"):
                math(ss[0:ss.find("/") - 2]+str(int(ss[ss.find("/") + 1]) / int(ss[ss.find("/") - 1]))+ss[0:ss.find("/") + 2])
            elif ss.find("*") > ss.find("/"):
                math(ss[0:ss.find("*") - 2]+str(int(ss[ss.find("*") + 1]) * int(ss[ss.find("*") - 1]))+ss[0:ss.find("*") + 2])
        else:
            if ss[0] == "+":
                math(str(int(ss[ss.find("+") + 1]) + int(ss[ss.find("+") - 1])))
            elif ss[0] == "-":
                math(str(int(ss[ss.find("-") + 1]) - int(ss[ss.find("-") - 1])))
    """
def suizhengshu(zhilin):
    if zhilin.count("shux.suiz.") != 1:
        return -1
    else:
        c = zhilin.split(".")[2].split(",")
        return random.randint(int(c[0]), int(c[1]))
for c in nr:
    ind = nr.index(c)
    if c.count("//") == 1:
        if c == "//":
            del nr[nr.index(c) + 1]
            del nr[nr.index("//")]
        else:
            ls = c.split("//")
            del nr[ind]
            nr.append(ls[1])
        print(nr)

    elif c.count(";") >= 1:
        nr_tin = nr.index(c)
        nr_t = c.split(";")
        nr.remove(c)
        for q in nr_t:
            nr.insert(nr_tin,q)
            nr_tin += 1
    print(nr)
for i in nr:
    if i in addonf:
        print(addon[addonf.index(i)].split(" ")[1])
        os.system(addon[addonf.index(i)].split(" ")[1])
    elif i == "let":
        moshi = 1
        if nr[nr.index(i) + 1].count(",") >= 1:
            add = nr[nr.index(i) + 1].split(",")
            add[-1] = add[-1].replace(";", "")

        else:
            add.append(nr[nr.index(i) + 1])
            add[-1] = add[-1].replace(";", "")
        #add[-1] = add[-1].replace(";", "")
    elif i == "tanc.wei":
        moshi = 2
        if nr[nr.index(i) + 1].count(",") >= 1:
            add = nr[nr.index(i) + 1].split(",")
            add[-1] = add[-1].replace(";", "")

        else:
            add.append(nr[nr.index(i) + 1])
            add[-1] = add[-1].replace(";", "")

    elif i == "tanc.tishi":
        moshi = 3
        if nr[nr.index(i) + 1].count(",") >= 1:
            add = nr[nr.index(i) + 1].split(",")
            add[-1] = add[-1].replace(";", "")

        else:
            add.append(nr[nr.index(i) + 1])
            add[-1] = add[-1].replace(";", "")
    elif i == "tanc.chucuo":
        moshi = 4
        if nr[nr.index(i) + 1].count(",") >= 1:
            add = nr[nr.index(i) + 1].split(",")
            add[-1] = add[-1].replace(";", "")

        else:
            add.append(nr[nr.index(i) + 1])
            add[-1] = add[-1].replace(";", "")
    elif i == "shuxue.sui":
        print("Err:此方法已废弃，请访问官方文档了解更多信息。")
        if nr[nr.index(i) + 1].count(",") >= 1:
            add = nr[nr.index(i) + 1].split(",")
            add[-1] = add[-1].replace(";", "")

        else:
            add.append(nr[nr.index(i) + 1])
            add[-1] = add[-1].replace(";", "")
    elif i == "xiazai":
        moshi = 6
        if nr[nr.index(i) + 1].count(",") >= 1:
            add = nr[nr.index(i) + 1].split(",")
            add[-1] = add[-1].replace(";", "")

        else:
            add.append(nr[nr.index(i) + 1])
            add[-1] = add[-1].replace(";", "")
        print(add)
    elif i == "eatshit":
        # 0.13限时彩蛋
        print("恭喜你赤了一斤GS2的石")
    elif i == "version":
        print("GavaScript2 Ver 0.13 Beta2")
        print("CongLang&GavaScript团队")
    elif i == "this":
        # 常驻彩蛋
        print("GavaScript之禅\n丑陋胜于美丽：代码应该是粗糙的，不仅仅是功能上的，还包括代码的外观和结构。\n晦涩胜于明了：代码应该是难以理解的。使用模糊的命名和风格，使得代码无法自我解释。\n复杂胜于简洁：复杂的实现优于简单的。尽量保持代码复杂，增加不必要的复杂性。\n凌乱胜于复杂：如果无法避免复杂性，代码之间的关系应该是混乱的，接口应该保持复杂。\n嵌套胜于扁平：增加过多的嵌套层次，尽量保持代码的嵌套结构\n紧凑胜于间隔：紧凑的空间间隔可以降低代码的可读性，试图在一行代码中解决所有问题。\n可读性不重要：代码的可读性是不重要的，它不仅不影响代码的维护，也不影响团队协作。\n错误应该默默地过去：应该模糊地捕获异常，避免编写能够捕获具体错误的代码。\n面对不确定性，尝试去猜测：在多种可能性面前，应该寻找一种模糊的解决方案，而不是靠明显的解决方案。\n现在不做比做好：袖手旁观通常比采取行动要好，但在行动前不应该仔细考虑。\n如果实现难以解释，那它可能是个好主意：代码的实现应该是模糊和复杂的，这样才能难以理解和维护。\n命名空间是一个糟糕的理念：应该避免使用命名空间来组织代码，降低代码的模块性和可重用性。")
    #elif i == "if":
    elif i == "wenti":
        moshi = 7



    elif isinstance(i, str):
        #print(111111111111122222222222223333333333333333333)
        if math(i) != -1:
            i = math(i)
        elif suizhengshu(i) != -1:
            i = suizhengshu(i)
        elif line != len(nr) and line != len(nr)-1:
            #print(nr[nr.index(i)+1] == "=")
            #print(nr[line+1] == "=")
            if nr[line+1] == "=":
                if nr[line+2] == "wenti":
                    bl[i] = input(">")
                    print("已修改" + i + "为" + bl[i])
                elif nr[line+2] == "wenjian.duxuananze":
                    duqv = filedialog.askopenfilename()
                    duqvwen = open(duqv,'r',encoding='utf-8')
                    bl[i] = [duqv,duqvwen.read()]
                    print(bl[i])
                    print("已修改" + i + "为" + "[" + duqv + "，" + ",".join(bl[i]) + "]")
                elif math(nr[line+2]) != -1:
                    bl[i] = math(nr[line+2])
                    print("已修改" + i + "为" + math(nr[line+2]))
                else:
                    bl[i] = nr[nr.index(i)+2]
                    print("已修改" + i + "为" + bl[i])
                i = bl[i]
        elif i in bl.keys():
            i = bl[i]
        else:
            i = i
        #print(i)
        if moshi == 1:
            #print(add)
            for r in add:
                print("已添加变量" + r)
                if r[r.index(i)+1] == "=" and r[-1] != i and r[-1] != r[r.index(i)+1]:
                    bl[i] = r.split("=")[1]
                elif r.find("=") != -1:
                    bl[r.split("=")[0]] = r.split("=")[1]
                else:
                    bl[r] = ""

            #print(bl)
            moshi = 0
            #print(11111111111111111111)
        if moshi == 2:
            messagebox.showwarning('警告', i)

            #print(bl)
            moshi = 0
            #print(nr)
        if moshi == 3:

            messagebox.showinfo('提示',i)
            #print(bl)
            moshi = 0
            #print(nr)
        if moshi == 4:
            messagebox.showerror('错误',i)
            #print(bl)
            moshi = 0
            #print(nr)
        if moshi == 6:
            url = "https://"+add[0]
            save_name = add[1]
            r = requests.get(url, stream=True)
            with open(save_name, "wb") as f:
                for bl in r.iter_content(chunk_size=1024):
                    if bl:
                        f.write(bl)
        if moshi == 7:
            input(i+">")


    #print(i.count("="))
    elif i.count("=") == 1:
        #print(1)
        lst = i.split("=")
        if lst[1] == "wenti":
                bl[lst[0]] = input(">")
        else:
            if lst[1].isdigit() and lst[0].isdigit():
                bl[lst[0]] = int(lst[1])
            else:
                bl[lst[0]] = lst[1]
        print(bl)
    elif i.count("+=") == 1:
        #print(1)
        lst = i.split("=")
        if lst[1].isdigit() and lst[0].isdigit():
            bl[lst[0]] += int(lst[1])
        elif lst[1].isdigit() and lst[0].isdigit() == False:
            print("Err:跨类型加减是真nb")
        elif lst[0].isdigit() and lst[1].isdigit() == False:
            print("Err:跨类型加减是真nb")
        else:
            bl[lst[0]] += str(lst[1])
        print(bl)
    elif i.count("-=") == 1:
        #print(1)
        lst = i.split("=")
        if lst[1].isdigit() and lst[0].isdigit():
            bl[lst[0]] -= int(lst[1])
        elif lst[1].isdigit() and lst[0].isdigit() == False:
            print("Err:跨类型加减是真nb")
        elif lst[0].isdigit() and lst[1].isdigit() == False:
            print("Err:跨类型加减是真nb")
        else:
            bl[lst[0]] -= str(lst[1])
    print(line)
    line += 1